package cn.outmaneuver.outman.web.basic.advice;
/**
 * Copyright 2023-2023 by DongYaoMing. All Rights Reserved.
 */

import cn.outmaneuver.outman.web.basic.domain.entity.GlobalLogDO;
import cn.outmaneuver.outman.web.basic.domain.response.StandardResult;
import cn.outmaneuver.outman.web.basic.service.GlobalHandlerService;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

/**
 * LogHandlerAdvice
 * <p>统一日志处理拦截器</p>
 *
 * @author DongYaoMing
 * @version 1.0
 * @date 2023/09/27
 */
@RestControllerAdvice
//@Slf4j
public class GlobalLogHandlerAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private GlobalHandlerService globalHandlerService;

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object resultData, MethodParameter methodParameter, MediaType mediaType, Class<?
            extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        try {
            String parameter = getParameter((HttpServletRequest) serverHttpRequest);
            if(resultData instanceof StandardResult){
                StandardResult resultBO = (StandardResult)resultData;
                String code = resultBO.getCode();
                String message = resultBO.getMessage();
                GlobalLogDO globalLogDO = new GlobalLogDO();
            }


        }catch (IOException ioException){
//            log.error();
        }
        return resultData;
    }

    private String getParameter(HttpServletRequest request) throws IOException {
        Map<String, String[]> queryParam = request.getParameterMap();
        BufferedReader bufferedReader = request.getReader();
        StringBuilder bodyParam = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            bodyParam.append(line);
        }

        JSONObject parameter = JSON.parseObject(bodyParam.toString());
        if (parameter == null) {
            parameter = new JSONObject();
        }
        parameter.putAll(queryParam);
        return parameter.toJSONString();
    }
}
